<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
      #id__stream {
        transform: rotateY(180deg);
      }
    </style>
  </head>
  <body>
    <div>

      <button id="start">开始</button>
      <button id="stop">停止</button>
    </div>
    <div>
      <video autoplay controls id="id__stream"></video>
    </div>
    <script>
      // 只获取视频
      let constraints = { audio: false, video: true };
      let startBtn = document.getElementById('start');
      let stopBtn = document.getElementById('stop');
      let videoShowControl = document.getElementById('id__stream');
      startBtn.onclick = function () {
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then(function (stream) {
            videoShowControl.srcObject = stream;
            window.stream = stream;
          })
          .catch(function (err) {
            console.log(err);
          });
      };

      function close(pause) {
        if (pause) {
          // 暂停
          videoShowControl.pause();
          return;
        }

        //关闭摄像头数据流
        if (videoShowControl.srcObject) {
          try {
            var tracks = videoShowControl.srcObject.getTracks();
            for (var track of tracks) {
              track.stop(); // 停止
            }
          } catch (e) {
            alert(e);
          }
        }
      }
      stopBtn.onclick = close;

      // 数据获取 https://blog.csdn.net/weixin_35959554/article/details/118220438
    </script>
  </body>
</html>
